﻿var acceptClick;
var keyValue = request('keyValue');
// 设置权限
var setAuthorize;
// 设置表单数据
var setFormData;
// 验证数据是否填写完整
var validForm;
// 保存数据
var save;

var isUpdate = false;

var bootstrap = function ($, learun) {
    "use strict";

    var userinfo;

    // 设置权限
    setAuthorize = function (data) {
       userinfo = learun.clientdata.get(['userinfo']);
        $("#createUsername").val(userinfo.user.realName);
        $('#postname').val(userinfo.user.postNames);
        //报销人
        $("#userid").lrformselect({
            layerUrl: config.webportal_server + 'pages/system/user/selectOnlyForm.html?companyId=' + userinfo.user.companyId + '&access_token=' + config.getToken().access_token,
            layerUrlW: 400,
            layerUrlH: 300,
            dataUrl: config.base_server() + 'users/getNames?access_token=' + config.getToken().access_token,
            select: function (item) {
                $.ajax({
                    url: config.base_server() + 'users/getPostname?keyValue=' + item.value + '&access_token=' + config.getToken().access_token,
                    data: {},
                    type: 'GET',
                    success: function (res) {
                        if (!!res.data) {
                            $('#postname').val(res.data);
                        }
                    }
                });
            }
        }).lrformselectSet(userinfo.user.id);

        $('#gridTable').css("width", $('.lr-form-wrap').width() - 60);

        $('#btn_reference').on('click', function () {
            learun.layerForm({
                id: 'selectForm',
                title: '选择报销单',
                url: config.webportal_server + 'pages/bill/selectForm.html?categoryId=1&schemeCode=bill_other1&access_token=' + config.getToken().access_token,
                width: 800,
                height: 500,
                callBack: function (id) {
                    return top[id].acceptClick(referenceSelect);
                }
            });
        });

        //加载费用表格
        initGridCost();

        //禁用输入框自动填充
        $("input[type='text']").each(function (index) {
            this.autocomplete = "off";
        });
    };
    var page = {
        init: function () {
            $('.lr-form-wrap').lrscroll();
            page.bind();
            page.initData();
        },
        bind: function () {

        },
        initData: function () {

        }
    };
    // 设置表单数据
    setFormData = function (processId,param,callback) {
        if (!!processId) {
            $('#filesInvoice').lrUploader({isView: false, processId: processId, isInvoice: 1});
            $('#filesInvoice_demo').on('click', function () {
                previewFile(config.base_server() + "profile/upload/temp/invoice.png");
            });

            $('#filesList').lrUploader({isView: false});
            $('#filesList_demo').on('click', function () {
                previewFile(config.base_server() + "profile/upload/temp/list.png");
            });
             $.lrSetForm(config.base_server() + 'other2s/findByProcessId?processId=' + processId, function (data) {
                 if (data != null) {
                    isUpdate = true;
                    $('#form').lrSetFormData(data);
                    $("#processCode").html(data.processCode);
                    $('#gridtable_cost').jfGridSet('refreshdata', data.costList);
                    if (data.costList.length < 6) {
                        for (var i = data.costList.length; i < 6; i++) {
                            $('#gridtable_cost').jfGridSet('addRow', {});
                        }
                    }
                } else {
                    $("#destination").citypicker();
                }
             });
        }
        callback && callback();
        $('#lr-layout-panel-right', window.parent.document).show();
    }
    // 验证数据是否填写完整
    validForm = function () {
        if (!$('body').lrValidform()) {
            return false;
        }
        return true;
    };
    // 保存数据
    save = function (processId, callBack, i) {

       var keyValue = "";

       if (isUpdate) {
           keyValue = processId;
       }

       var formData = $('#form').lrGetFormData();

       var costData = [];
       var costDataTmp = $('#gridtable_cost').jfGridGet('rowdatas');

       if (costDataTmp.length == 0) {
           learun.alert.error('费用清单信息不全,请检查！');
           return false;
       }
       for (var x = 0, l = costDataTmp.length; x < l; x++) {
           if (!!costDataTmp[x]['itemCode']) {
               if (!costDataTmp[x].money) {
                   learun.alert.error('第'+(x+1)+'行金额非法');
                   return;
               }
               costDataTmp[x].sort = x;
               costData.push(costDataTmp[x]);
           }
       }

       var postData = formData;
       postData.id = parent.processId;
       postData.processId = processId;
       postData.costList = costData

       $.lrSaveForm(config.base_server() + 'other2s/saveOrUpdate?keyValue=' + keyValue + '&force=' + 1 + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
           if (res.resp_code != 200) {
               $("#errorMsg").show();
               var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                   "            <p>提示：</p>\n" +
                   "            <p>" + res.resp_msg + "</p>\n" +
                   "        </div>"
               $("#gridtable_cost").css("border", "1px solid red;");
               $("#errorMsg").html(html);
           } else {
               $("#errorMsg").hide();
               var html = "<div class=\"alert alert-danger\" role=\"alert\">\n" +
                   "        </div>"
               $("#gridtable_cost").css("border", "1px solid #ddd;");
               $("#errorMsg").html(html);

               // 保存成功后才回调
               if (!!callBack) {
                   callBack(res, i);
               }
           }
       });

    };

    //加载子表格
    function initGridCost() {
        $('#gridtable_cost').jfGrid({
            headData: [
                {
                    label: '事项', name: 'itemCode', width: 200, align: 'center',
                    edit: {
                        type: 'input'
                    }
                },

                {
                    label: '金额', name: 'money', width: 200, align: 'center', statistics: true,
                    formatter: function (cellvalue) {
                        return $.formatMoney(cellvalue, 2);
                    },
                    edit: {
                        type: 'number',
                        init: function (data, $edit) {// 在点击单元格的时候触发，可以用来初始化输入控件，行数据和控件对象
                        },
                        change: function (data, num) {// 行数据和行号

                        }
                    }
                },

                {
                    label: '费用说明', name: 'remark', width: 200, align: 'left',
                    edit: {
                        type: 'input',
                    }
                }
            ],
            isEdit: true,
            isMultiselect: true,
            // onAddRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // onMinusRow: function (row, rows) {//行数据和所有行数据
            //
            // },
            // beforeMinusRow: function (row) {// 行数据 返回false 则不许被删除
            //     return true;
            // }
        });
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
        $('#gridtable_cost').jfGridSet('addRow', {});
    }

    //文件预览
    function previewFile(url) {
        learun.layerForm({
            id: 'PreviewUrl',
            title: '文件预览',
            url: config.webportal_server + 'pages/utility/previewUrl.html?url=' + url + '&access_token=' + config.getToken().access_token,
            width: 700,
            height: 850,
            btn: null
        });
    }

    page.init();
}
